package com.icexxx.icemock.util;

import java.util.ArrayList;
import java.util.List;

import com.icexxx.icemock.pojo.Feather;
import com.icexxx.icemock.pojo.Peafowl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

public class MockBattery {
	public static Feather analysisFeather(String line) {
		line = StrUtil.trim(line);
		String str = line;
		String name = null;
		String expression = null;
		if (line.contains(":=")) {
			name = StrUtil.subBefore(str, ":=", false);
			expression = StrUtil.subAfter(str, ":=", false);
		} else if (line.contains(":")) {
			name = StrUtil.subBefore(str, ":", false);
			expression = StrUtil.subAfter(str, ":", false);
		} else if (line.contains("=")) {
			name = StrUtil.subBefore(str, "=", false);
			expression = StrUtil.subAfter(str, "=", false);
		} else {
			return null;
		}
		name = StrUtil.trim(name);
		expression = StrUtil.trim(expression);
		Feather feather = new Feather();
		feather.setName(name);
		feather.setExpression(expression);
		return feather;
	}

	public static int analysisCount(String line) {
		String str = line.replaceAll("=+", "=");
		str = StrUtil.trim(str);
		if (str.contains("*")) {
			int index = str.indexOf("*");
			StringBuilder sb = new StringBuilder();
			for (int i = index + 1; i < str.length(); i++) {
				char ch = str.charAt(i);
				if (Character.isDigit(ch)) {
					sb.append(ch);
				} else {
					break;
				}
			}
			String countStr = sb.toString();
			return Integer.parseInt(countStr);
		}
		return 0;
	}

	public static String analysisTableName(String line) {
		String str = line.replaceAll("=+", "=");
		str = StrUtil.trim(str);
		boolean isWord = false;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if (Character.isLetter(ch)) {
				sb.append(ch);
				isWord = true;
			} else if (ch == '=') {
				if (isWord) {
					String tableName = sb.toString();
					return tableName;
				}
				isWord = false;
			} else if (Character.isDigit(ch) || ch == '_' || ch == '-') {
				if (isWord) {
					sb.append(ch);
				}
			}
		}
		String tableName = sb.toString();
		if (StrUtil.isNotBlank(tableName)) {
			return tableName;
		}
		return null;
	}

	public static void mockData(List<Peafowl> peafowlList) {
		List<String> insertSqlList = new ArrayList<>();
		if(CollUtil.isNotEmpty(peafowlList)) {
			for (int i = 0; i < peafowlList.size(); i++) {
				Peafowl peafowl = peafowlList.get(i);
				int count = peafowl.getCount();
				for (int j = 0; j < count; j++) {
					String sql = DatabaseBattery.convertSql(peafowl, j);
					if(StrUtil.isNotBlank(sql)) {
						insertSqlList.add(sql);
					}
				}
			}
		}
		DatabaseBattery.executeSql(insertSqlList);
	}
}
